package com.ruoyi.system.mapper.typeHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class MyMapTypeHandler implements TypeHandler<Map<String, Object>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType) throws SQLException {
        // 将 Map 对象转换为字符串并设置到 PreparedStatement 中
        String value = null;
        try {
            value = new ObjectMapper().writeValueAsString(parameter);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        ps.setString(i, value);
    }

    @Override
    public Map<String, Object> getResult(ResultSet rs, String columnName) throws SQLException {
        // 从 ResultSet 中获取字符串，并将其转换为 Map 对象
        String value = rs.getString(columnName);
        return parseJsonString(value);
    }

    @Override
    public Map<String, Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从 ResultSet 中获取字符串，并将其转换为 Map 对象
        String value = rs.getString(columnIndex);
        return parseJsonString(value);
    }

    @Override
    public Map<String, Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从 CallableStatement 中获取字符串，并将其转换为 Map 对象
        String value = cs.getString(columnIndex);
        return parseJsonString(value);
    }

    // 将 JSON 字符串转换为 Map 对象
    private static Map<String, Object> parseJsonString(String value) throws SQLException {
        try {
            return new ObjectMapper().readValue(value, new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            throw new SQLException("Failed to parse JSON string", e);
        }
    }
}
